package com.truthbean.jeetb.utils.server;

import com.truthbean.jeetb.utils.StringUtils;
import org.apache.tomee.embedded.Configuration;
import org.apache.tomee.embedded.Container;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by TruthBean on 2016-10-17 12:54.
 */
//ERROR!!!
public class TomEEUtils {
    private static final String CONTEXT_PATH  = "jeetb.web.tomcat.context-path";
    private static final String PORT = "jeetb.web.tomcat.port";
    private File file = new File(getClass().getClassLoader().getResource("app.properties").getFile());

    private int httpPort() {
        String port = System.getenv("PORT");
        return port == null?8080:Integer.parseInt(port);
    }

    private Configuration configuration(){
        Configuration configuration = new Configuration();
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("app.properties is not found in resources");
        }
        if(properties.containsKey(PORT)){
            String httpPortStr = properties.getProperty(PORT);
            if(StringUtils.isNumber(httpPortStr)){
                int httpPort = Integer.parseInt(httpPortStr);
                configuration.http(httpPort);
            } else {
                configuration.http(httpPort());
            }
        }
        configuration.dir(file.getParentFile().getParent());
        return configuration;
    }

    public void run(){
        Container container = (new Container(configuration())).deployClasspathAsWebApp("", new File(file.getParentFile().getParent() + "cms.war"), new String[0]);
        Throwable var2 = null;

        try {
            container.await();
        } catch (Throwable var11) {
            var2 = var11;
            throw var11;
        } finally {
            if(container != null) {
                if(var2 != null) {
                    try {
                        container.close();
                    } catch (Throwable var10) {
                        var2.addSuppressed(var10);
                    }
                } else {
                    container.close();
                }
            }

        }
    }
}
